package cn.edu.zut.dao;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import cn.edu.zut.domain.Employee;

@Repository
public class EmployeeDao {
    private JdbcTemplate jdbcTemplate;
    private final static String  MATCH_COUNT_SQL = " SELECT count(*) FROM t_employee  " +
            " WHERE employee_name =? and password=? ";
    private final static String UPDATE_LOGIN_INFO_SQL = " UPDATE t_employee SET " +
            " last_visit=?,last_ip=?,credits=?  WHERE employee_id =?";
    public int getMatchCount(String employeeName, String password) {

        return jdbcTemplate.queryForObject(MATCH_COUNT_SQL, new Object[]{employeeName, password}, Integer.class);
    }

    public Employee findEmployeeByEmployeeName(final String employeeName) {
        String sqlStr = " SELECT employee_id,employee_name,credits "
                + " FROM t_employee WHERE employee_name =? ";
        final Employee employee = new Employee();
        jdbcTemplate.query(sqlStr, new Object[]{employeeName},
                //？？？匿名类方式实现的回调函数,负责将查询到的结果从ResultSet装载到类似于领域对象的对象实例employee中
                new RowCallbackHandler() {
                    public void processRow(ResultSet rs) throws SQLException {
                        employee.setEmployeeId(rs.getInt("employee_id"));
                        employee.setEmployeeName(employeeName);
                        employee.setCredits(rs.getInt("credits"));
                    }
                });
        return employee;
    }

    public void updateLoginInfo(Employee employee) {
        jdbcTemplate.update(UPDATE_LOGIN_INFO_SQL, new Object[] { employee.getLastVisit(),
                employee.getLastIp(),employee.getCredits(),employee.getEmployeeId()});
    }

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}



